import { defineStore } from 'pinia'
import _ from 'lodash'

export const useTagsViewStore = defineStore('tagsViewStore', {
  state: () => {
    return {
      visitedViews: [],
      cachedViews: []
    }
  },
  getters: {
    firstViews: (state) =>
      _.isEmpty(state.visitedViews) ? undefined : state.visitedViews[0],
    lastViews: (state) =>
      _.isEmpty(state.visitedViews)
        ? undefined
        : state.visitedViews[state.visitedViews.length - 1]
  },
  actions: {
    // resetCachedViews() {
    //   this.cachedViews = _.isEmpty(this.visitedViews) ? [] : this.visitedViews.filter(item => item.meta.cache === true)
    // },

    addView(view) {
      const index = this.visitedViews.findIndex((v) => v.path === view.path)
      index === -1 &&
        this.visitedViews.push(
          Object.assign({}, view, {
            title: view.meta.title || 'undefined'
          })
        )

      this.addCachedViews(view)
    },

    addCachedViews(view) {
      // console.log(view, 'addCachedViews')
      const index = this.cachedViews.indexOf(view.name)
      index === -1 && this.cachedViews.push(view.name)
    },

    deleteView(view) {
      for (const [i, v] of this.visitedViews.entries()) {
        if (v.path === view.path) {
          this.visitedViews.splice(i, 1)
          return i
        }
      }
      this.deleteCachedViews(view)
    },

    deleteCachedViews(view) {
      const index = this.cachedViews.indexOf(view.name)
      index > -1 && this.cachedViews.splice(index, 1)
    },

    deleteOthersViews(view) {
      this.visitedViews = this.visitedViews.filter((v) => {
        return v.meta.affix || v.path === view.path
      })
      this.resetCachedViews()
    },

    resetCachedViews() {
      this.cachedViews = []
      for (const item of this.visitedViews) {
        if (item.meta?.cache === true) {
          this.cachedViews.push(item.name)
        }
      }
    },

    deleteAllViews() {
      this.visitedViews = this.visitedViews.filter((tag) => tag.meta.affix)
      this.resetCachedViews()
    },

    deleteRightViews(view) {
      const index = this.visitedViews.findIndex((v) => v.path === view.path)
      if (index === -1) {
        return
      }
      this.visitedViews = this.visitedViews.filter(
        (item, idx) => idx <= index || (item.meta && item.meta.affix)
      )
      this.resetCachedViews()
    },
    deleteLeftViews(view) {
      const index = this.visitedViews.findIndex((v) => v.path === view.path)
      if (index === -1) {
        return
      }
      this.visitedViews = this.visitedViews.filter(
        (item, idx) => idx >= index || (item.meta && item.meta.affix)
      )
      this.resetCachedViews()
    }
  }
})

export default useTagsViewStore
